package org.meb.speedway.process;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ServiceLoader;

import org.meb.speedway.model.common.IntEvent;
import org.meb.speedway.process.model.EventData;

public class EventTaskProcessorChain {

	private static EventTaskProcessorChain instance;
	private List<EventTaskProcessor> processors;

	public synchronized static EventTaskProcessorChain getInstance() {
		if (instance == null) {
			instance = new EventTaskProcessorChain();
		}
		return instance;
	}

	private EventTaskProcessorChain() {
		processors = new ArrayList<EventTaskProcessor>();
		ServiceLoader<EventTaskProcessor> loader = ServiceLoader.load(EventTaskProcessor.class);
		Iterator<EventTaskProcessor> iterator = loader.iterator();
		while (iterator.hasNext()) {
			processors.add(iterator.next());
		}
	}

	public void process(IntEvent eventTask) {
		for (EventTaskProcessor processor : processors) {
			try {
				EventData eventData = processor.process(eventTask);
				if (eventData != null) {
					break;
				}
				// no problem - go to next processor
			} catch (EventTaskProcessException e) {
				e.printStackTrace();
				// no problem - go to next processor
			}
		}
	}
}
